package com.tanhua.commons.template;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.tanhua.commons.properties.BaiduAipFaceProperties;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.util.HashMap;

@Slf4j
public class BaiduAipFaceTemplate {
    private AipFace client;

    public BaiduAipFaceTemplate(BaiduAipFaceProperties properties) {
        client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecretKey());
    }

    /**
     * 人脸检测
     * @param bytes 图片的字节数组
     * @return true表示检测到了人脸；false表示没有检测到人脸
     */
    public boolean detect(byte[] bytes){
        // 调用接口
        String image = Base64Util.encode(bytes);
        String imageType = "BASE64";

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("max_face_num", "1");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");

        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);

        log.info("人脸检测结果: {}", res.toString(2));

        int errorCode = res.getInt("error_code");
        if (errorCode == 0) {
            int faceNum = res.getJSONObject("result").getInt("face_num");
            return faceNum > 0;
        }
        return false;
    }
}